import React, { useState } from 'react';
import { SortableContainer, SortableElement } from 'react-sortable-hoc';
import ProTable from '@ant-design/pro-table';
import './drag.less';
import { arrayMoveImmutable } from '@ant-design/pro-utils';
const CurrentBraftEditor: React.FC<any> = (
    {  headerTitle,columns, pagination, orderByRequest,data ,actionRef,toolBarRender},

) => {
        const [dataSource, setDataSource] = useState(data);
        const SortableItem = SortableElement((props: any) => <tr {...props} />);
        const SortContainer = SortableContainer((props: any) => <tbody {...props} />);
        const onSortEnd = ({oldIndex, newIndex}: { oldIndex: number; newIndex: number }) => {
            console.log(oldIndex, newIndex)
            if (oldIndex !== newIndex) {
                const newData = arrayMoveImmutable([...dataSource], oldIndex, newIndex).filter((el) => !!el);
                let array = [];
                newData.map((_, index) => {
                    array.push(_.id)
                    console.log(_, index)
                })
                orderByRequest(array)
                console.log(array, 'new')
                setDataSource([...newData]);
            }
        };
        const DraggableContainer = (props: any) => (
            <SortContainer
                useDragHandle
                disableAutoscroll
                helperClass="row-dragging"
                onSortEnd={onSortEnd}
                {...props}
            />
        );

        const DraggableBodyRow = (props: any) => {
            const {className, style, ...restProps} = props;
            console.log(restProps)
            // function findIndex base on Table rowKey props and should always be a right array index
            const index = dataSource.findIndex((x) => x.id === restProps['data-row-key']);
            return <SortableItem index={index} {...restProps} />;
        };

        return (
            <ProTable
                headerTitle={headerTitle}
                columns={columns}
                rowKey="id"
                actionRef={actionRef}
                pagination={pagination?pagination:false}
                dataSource={dataSource}
                toolBarRender={toolBarRender}
                components={{
                    body: {
                        wrapper: DraggableContainer,
                        row: DraggableBodyRow,
                    },
                }}
            />
        );


}
export default CurrentBraftEditor;